from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Task_Machine_schema
from controller import Task_Machine_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Task_Machine", response_model=Task_Machine_schema.Task_machine, tags=["Task_Machine"])
async def create_Task_Machine(Task_Machine: Task_Machine_schema.Task_machine, db: Session = Depends(get_db)):
    return Task_Machine_controller.create_Task_Machine(db, Task_Machine)


@router.get("/Task_Machine/{ID}", response_model=Task_Machine_schema.Task_machine, tags=["Task_Machine"])
async def get_Task_Machine(ID: int, db: Session = Depends(get_db)):
    db_Task_Machine = Task_Machine_controller.get_Task_Machine(db, ID)
    if db_Task_Machine is None:
        raise HTTPException(status_code=404, detail="Task_Machine not found")
    return db_Task_Machine


@router.get("/Task_Machine", response_model=List[Task_Machine_schema.Task_machine], tags=["Task_Machine"])
async def get_all_Task_Machine(db: Session = Depends(get_db)):
    all_db_Task_Machine = Task_Machine_controller.get_all_Task_Machine(db)
    if all_db_Task_Machine is None:
        raise HTTPException(status_code=404, detail="0 Task_Machine found, empty table")
    return all_db_Task_Machine


@router.put("/Task_Machine/{ID}", tags=["Task_Machine"])
async def update_Task_Machine(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Task_Machine = Task_Machine_controller.update_Task_Machine(db, ID, field_name, field_value)
        if db_Task_Machine is None:
            raise HTTPException(status_code=404, detail="Task_Machine not found")
        return db_Task_Machine
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Task_Machine/{ID}", tags=["Task_Machine"])
async def delete_Task_Machine(ID: int, db: Session = Depends(get_db)):
    is_deleted = Task_Machine_controller.delete_Task_Machine(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
